/*
 * Copyright (c) 2020 Nanjing Xiaoxiongpai Intelligent Technology Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <unistd.h>

#include "cmsis_os2.h"
#include "ohos_init.h"
#include "los_membox.h"

#define MEMBOX_POOL_SIZE    100
#define MEMBOX_BLOCK_SZIE   10
#define MEMBOX_WR_TEST_NUM  828

void memory_entry(){
    UINT32 *mem = NULL;
    UINT32 blkSize = MEMBOX_BLOCK_SZIE;
    UINT32 poolSize = MEMBOX_POOL_SIZE;
    UINT32 boxMem[MEMBOX_POOL_SIZE];
    UINT32 ret;

    /* 内存池初始化 */
    ret = LOS_MemboxInit(&boxMem[0], poolSize, blkSize);
    if(ret != LOS_OK) {
        printf("Membox init failed!\n");
        return;
    } else {
        printf("Membox init success!\n");
    }
    printf("内存池起始地址是 0x%x\n",boxMem);
    printf("块大小 %d 块总数 %d 已经使用块数 %d 下一个可以分配的块地址 0x%x\n",\
            boxMem[0], boxMem[1], boxMem[2], boxMem[3]);


    /* 申请内存块 */
    mem = (UINT32 *)LOS_MemboxAlloc(boxMem);
    if (mem == NULL) {
        printf("Mem alloc failed!\n");
        return;
    }
    printf("Mem alloc success!\n");
    printf("块大小 %d 块总数 %d 已经使用块数 %d 下一个可以分配的块地址 0x%x\n",\
            boxMem[0], boxMem[1], boxMem[2], boxMem[3]);
    /* 内存地址读写验证 */
    *mem = MEMBOX_WR_TEST_NUM;
    printf("*mem = %d\n", *mem);

    /* 清除内存内容 */
    LOS_MemboxClr(boxMem, mem);
    printf("Mem clear success \n*mem = %d\n", *mem);

    /* 释放内存 */
    ret = LOS_MemboxFree(boxMem, mem);
    if (LOS_OK == ret) {
        printf("Mem free success!\n");
    } else {
        printf("Mem free failed!\n");
    }

    return;
}
